﻿using System;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using SalesSys.BLL;
using SalesSys.Comm.BLL;
using SalesSys.Comm.Utility;
using SalesSys.DAL.Models;

namespace SalesSys.WebCore.Authorize
{
    /// <summary>
    /// 前台用户相关帮助类
    /// </summary>
   public static class ClientHelper
    {
       public readonly static string SessionUserInfoSign = "_userInfo";
       public readonly static string UserAuthName = "_user";
       //用户角色标记
       public readonly static string StudentRoleSign = "student";
       public readonly static string TeacherRoleSign = "teacher";

     


        /// <summary>
        /// 是否是微信访问
        /// </summary>
        /// <returns></returns>
        public static bool IsWechat()
       {
           bool isWechat = HttpContext.Current.Request.UserAgent.ToLower().Contains("micromessenger");
           return isWechat;
       }
       
       /// <summary>
       /// 获取当前用户登录信息
       /// </summary>
       public static IEmployee ClientInfo
       {
           get
           {
               return GetInfo<Employee>(UserAuthName, SessionUserInfoSign, null);
           }
       }
       public static Employee GetInfo(HttpSessionState session)
       {
           return session[SessionUserInfoSign] as Employee;
       }
      
    
       /// <summary>
       /// 获取上下文中指定用户信息,并验证是否是登录的。内部工具类不应直接使用
       /// </summary>
       /// <typeparam name="T"></typeparam>
       /// <param name="authName"></param>
       /// <param name="sessionInfoSign"></param>
       /// <param name="contextBase"></param>
       /// <returns></returns>
       internal static T GetInfo<T>(string authName, string sessionInfoSign, HttpContextBase contextBase = null) where T:class
       {
           T info = null;
           if (contextBase == null)
           {
               var context = HttpContext.Current;
               var session = context.Session;
               info =session==null?null: session[sessionInfoSign] as T;
               //if (context.User != null && context.User.Identity.IsAuthenticated && context.User.Identity.Name == authName)   // 验证
               //{
               //    info = context.Session[sessionInfoSign] as T;
               //}
               //if (info == null && session != null)
               //{
               //    var list = BllFactory.GetBll<EmployeeBLL>().GetList(p => p.LoginName == "sa");
               //      session[sessionInfoSign] = list[0];
               //    info = list[0] as T;
               //}
           }
           else
           {
               var context = contextBase;
               var session = context.Session;
               info = session == null ? null : session[sessionInfoSign] as T;
               //if (context.User != null && context.User.Identity.IsAuthenticated && context.User.Identity.Name == authName)   // 验证
               //{
               //    info = context.Session[sessionInfoSign] as T;
               //}
           }
        
           return info;
       }

       /// <summary>
       /// 获取上下文中指定机构的信息，并验证是否登录
       /// </summary>
       /// <typeparam name="T"></typeparam>
       /// <returns></returns>
       internal static T GetOrganizationInfo<T>(string authName,string sessionInfoSign,HttpContextBase contextBase=null)where T:class
       {
           T info = null;
           if (contextBase == null)
           {
               var context = HttpContext.Current;
               var session = context.Session;
               info = session == null ? null : session[sessionInfoSign] as T;
           }
           else 
           {
             var context   =  contextBase;
             var  session   =context.Session;
             info =session== null ? null : session[sessionInfoSign] as T;
           }
           return info;
       }

       /// <summary>
       /// 针对机构信息存入到session的的指定名称里面
       /// </summary>
       /// <param name="authName"></param>
       /// <param name="sessionInfoSign"></param>
       /// <param name="data"></param>
       /// <param name="contextBase"></param>
       internal static void SetOrganizationInfo(string authName,string sessionInfoSign,object data,HttpContextBase contextBase=null)
       {
           if (contextBase == null)
           {
               HttpContext.Current.Session[sessionInfoSign] = data;
           }
           else
           {
               contextBase.Session[sessionInfoSign] = data;
           }
           FormsAuthentication.SetAuthCookie(authName , false);
       }

       internal static void SetInfo(string authName, string sessionInfoSign, object data, HttpContextBase contextBase = null)
       {
           if (contextBase == null)
           {
               HttpContext.Current.Session[sessionInfoSign] = data;
           }
           else
           {
               contextBase.Session[sessionInfoSign] = data;
           } 
           FormsAuthentication.SetAuthCookie(authName, false);
       }
      static void SetInfo(object data, HttpContextBase httpContext = null)
       {
           SetInfo(UserAuthName, SessionUserInfoSign, data, httpContext);
       }
       /// <summary>
       /// 检查当前用户是否拥有指定权限
       /// </summary>
       /// <param name="httpContext"></param>
       /// <param name="powerSignName"></param>
       /// <returns></returns>
       public static bool IsHaveRole(string roleSignName)
       {
           var info = ClientInfo;
           return info != null && info.IsRole(roleSignName); //.Roles.Any(p => p.Name == roleSignName);
       }

       /// <summary>
       /// 用户登录,如果登录成功将保存用户信息到session
       /// </summary>
       /// <param name="userName"></param>
       /// <param name="md5Pw"></param>
       /// <param name="salt"></param>
       /// <param name="httpContext"></param>
       /// <returns></returns>
       public static bool UserLoginAuth(HttpContextBase httpContext, string userName, string md5Pw, string salt = null)
       {
           if (string.IsNullOrWhiteSpace(userName) || string.IsNullOrWhiteSpace(md5Pw))
               return false;
           var user = BllFactory.GetBll<EmployeeBLL>().CheckPw(userName, md5Pw, salt);
           if (user == null)
               return false;
           if (user.IsLock)
           {
               return false;
           }
           SetUserLogin(httpContext, user);
           return true;
       }

       /// <summary>
       /// 将一个现有用户直接设置为登录
       /// </summary>
       /// <param name="httpContext"></param>
       /// <param name="user"></param>
       public static void SetUserLogin(HttpContextBase httpContext, Employee user)
       {
          // var roles = user.WXRoles.Select(p => new PrincipalInfo.Role() { Name = p.SignName }).ToArray();
           var info = user; //new PrincipalInfo(user.Id, user.Name, roles);
           SetInfo(info, httpContext);
           if (UserLoginSuccess != null)
           {
               try
               {
                   UserLoginSuccess.BeginInvoke(user, user, null, null);
               }
               catch (Exception ex)
               {
                   Log.m.Error("用户登录事件异步调用异常：" + ex);
                   throw;
               }
           }
       }

       /// <summary>
       /// 用户登录成功事件，包含成功登录用户的信息
       /// </summary>
       public static event Action<object, Employee> UserLoginSuccess;
   
       /// <summary>
       /// 注销用户，清空会话信息
       /// </summary>
       public static void OutLogin()
       {
           FormsAuthentication.SignOut();
           HttpContext.Current.Session.Clear();
           HttpContext.Current.Session.Abandon();
       }



      

    }
}
